{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rkJsyUdEtv48"
   },
   "source": [
    "# Chapter 8 - Miscellaneous - 其餘補充說明"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dygVGpmaC7Jz"
   },
   "source": [
    "筆者用了七個章節來介紹了筆者認為一定要理解的知識，這個章節則將剩餘的部分集合起來。這部分的知識不能說不重要，只是對於初學時來說，有些觀念易於混淆，有些則比較少有機會使用，比較沒有馬上需要理解的急迫性，所以集合在此。\n",
    "\n",
    "讀者們可以試著先嘗試理解，但如果不懂也沒有關係，等到前幾個章節都消化完、開發程式一段時間以後再回頭看，或許會更容易融會貫通！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hH-rr92wt7iU"
   },
   "source": [
    "## Tuples"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "j8vfojiaEQn8"
   },
   "source": [
    "Tuples 也是一種序列 (Sequence) 物件，與串列 Lists 不一樣的是，Tuples 的內容不可以再被更新，也就是屬於不可變型態 (Immutable) 的物件。\n",
    "\n",
    "建立 Tuples 的方法為：將物件用小括號 (`()`, Parentheses) 集合。雖然與運算時用的括號是一樣的，但用途卻不同。\n",
    "\n",
    "> 備註：關於 Tuples 物件，官方並沒有翻譯，比較常見的大概是元組、數對一類的名詞。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 811,
     "status": "ok",
     "timestamp": 1607863014703,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "NYRaJP6LpjDV",
    "outputId": "1c408742-1792-4756-fe37-d9ba5acafee0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Bird', 'Cat', 'Dog')\n",
      "<class 'tuple'>\n"
     ]
    }
   ],
   "source": [
    "t = (\"Bird\", \"Cat\", \"Dog\")  # 建立 Tuple 物件\n",
    "print(t)\n",
    "print(type(t))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1048,
     "status": "ok",
     "timestamp": 1607083842254,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "3GAK7BM6qEOB",
    "outputId": "1ffe3667-bac1-407e-92dd-27d981131a99"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dog\n"
     ]
    }
   ],
   "source": [
    "print(t[2])  # 索引\n",
    "# t[2] = \"Puppy\"  # 因為 Tuples 無法被修改，所以對其指定物件會發生錯誤"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 742,
     "status": "ok",
     "timestamp": 1607863102018,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "tGAoGepJG1Ug",
    "outputId": "3d4613c6-d931-4ca0-afa4-2b259b6715b9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bird\n",
      "Cat\n",
      "Dog\n"
     ]
    }
   ],
   "source": [
    "for animal in t:  # 因為也是序列物件，所以可以用 For loop 進行處理\n",
    "    print(animal)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 938,
     "status": "ok",
     "timestamp": 1607863572984,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "1xGApX52IMBj",
    "outputId": "31d7b8a2-5b6b-4b82-ab20-a80a3d306e92"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('A', 'B', 'C')\n",
      "<class 'tuple'>\n"
     ]
    }
   ],
   "source": [
    "l = [\"A\", \"B\", \"C\"]\n",
    "t = tuple(l)  # 要將其他序列型態物件轉換為 tuples，可以使用 tuple() 函式\n",
    "print(t)\n",
    "print(type(t))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WampJ2R-uDlf"
   },
   "source": [
    "## Sets：集合"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "將多個物件裝入成對大括號 `{}` 中，不要加上鍵，即形成集合物件。\n",
    "\n",
    "特性是內部沒有重複的物件，所以也可以將多個物件的型態轉換為集合，藉此消除重複的物件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1099,
     "status": "ok",
     "timestamp": 1607083918623,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "xb4vIgnhqWkp",
    "outputId": "f02bdee7-66eb-45ae-a17a-2b86971c14e0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4}\n",
      "<class 'set'>\n"
     ]
    }
   ],
   "source": [
    "s = {1, 2, 3, 4}\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "yEUga8k4qoMx"
   },
   "outputs": [],
   "source": [
    "# print(s[0])  # 集合不支援索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 687,
     "status": "ok",
     "timestamp": 1607084121735,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "oz6QNXRxrNpE",
    "outputId": "cbb9899d-9a00-45d5-fd73-2c5564af900b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4}\n"
     ]
    }
   ],
   "source": [
    "l = [1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4]\n",
    "s = set(l)  # 將串列轉換為集合\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[集合](https://zh.wikipedia.org/zh-tw/集合_(數學))還可以配合運算子做以下操作：\n",
    "\n",
    "* `|`：[聯集](https://zh.wikipedia.org/zh-tw/聯集)\n",
    "* `&`：[交集](https://zh.wikipedia.org/zh-tw/交集)\n",
    "* `-`：[差集](https://zh.wikipedia.org/zh-tw/差集)\n",
    "* `^`：[對稱差](https://zh.wikipedia.org/zh-tw/對稱差)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6}\n",
      "{1, 2}\n",
      "{3, 4}\n",
      "{3, 4, 5, 6}\n"
     ]
    }
   ],
   "source": [
    "a = {1, 2, 3, 4}\n",
    "b = {1, 2, 5, 6}\n",
    "\n",
    "print(a | b)  # 聯集\n",
    "print(a & b)  # 交集\n",
    "print(a - b)  # 差集 \n",
    "print(a ^ b)  # 對稱差"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "YSzcgugCxB1H"
   },
   "source": [
    "## Lambda expressions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "簡而言之：把函式寫成一行。通常會搭配接下來的小傑的函式來應用，也就是 `map()`, `filter()`, 跟 `reduce()`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bGGtJD2KxpzP"
   },
   "source": [
    "References:\n",
    "\n",
    "* [Lambda expressions - Python Documentation](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions)\n",
    "* [Lambdas - Python Documentation](https://docs.python.org/3/reference/expressions.html#lambda)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "8yeMussJy0NF"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "# 範例：add() 是個將兩數相加的函式\n",
    "def add(x, y):\n",
    "    return x + y\n",
    "\n",
    "print(add(1, 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "e8h6F4Rj28Bj"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "# 我們用 Lambda expression 改寫\n",
    "add = lambda x, y: x+y\n",
    "\n",
    "print(add(1, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "U5A4zZ8cthrH"
   },
   "source": [
    "## Additional useful built-in functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tJtDcPxQy636"
   },
   "source": [
    "### `map()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "將函式應用於疊代物件中的每個物件，並回傳結果。\n",
    "\n",
    "References:\n",
    "\n",
    "* [map() - Python Documentation](https://docs.python.org/3/library/functions.html#map)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 556,
     "status": "ok",
     "timestamp": 1606985496059,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "g81wU8LMzGX9",
    "outputId": "a2bd8a3b-5841-4472-93da-4552a2968206"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "numbers = list(range(1, 6))\n",
    "print(numbers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 779,
     "status": "ok",
     "timestamp": 1606985545148,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "vyWklrFVzLfj",
    "outputId": "44b55a5f-cac8-4796-ed3f-c3c4b8e9e384"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<map at 0x11037e4a8>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 直接套用會回傳 map 物件\n",
    "map(lambda x: x**2, numbers)  # 設計計算每個物件的平方數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 861,
     "status": "ok",
     "timestamp": 1606985582490,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "fxkseO3vzXi7",
    "outputId": "b57598c0-e09c-417a-c274-7a25255ddacc"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25]\n"
     ]
    }
   ],
   "source": [
    "# 讀取內容的方法之一：將型態轉換為串列\n",
    "squared_numbers = list(map(lambda x: x**2, numbers))\n",
    "print(squared_numbers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DoOTHdJmy8pt"
   },
   "source": [
    "### `filter()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "將函式套用到疊代物件中的每個物件，並回傳所有結果為 `True` 的物件，捨棄結果為 `False` 的物件。\n",
    "\n",
    "* [filter() - Python Documentation](https://docs.python.org/3/library/functions.html#filter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 791,
     "status": "ok",
     "timestamp": 1606985650710,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "Lkf66nfqzrze",
    "outputId": "31fdfd6d-cf52-4172-8b46-d8da35c0c22a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "numbers = list(range(1, 6))\n",
    "print(numbers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 796,
     "status": "ok",
     "timestamp": 1606985663614,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "BGLuyaGWzyhZ",
    "outputId": "d3b2a05e-e6b7-4b21-9197-0965bbdd73e1"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<filter at 0x1103945f8>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 直接套用會回傳 filter 物件\n",
    "filter(lambda x: x%2==0, numbers)  # 設計過濾掉非 2 的倍數的整數"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 527,
     "status": "ok",
     "timestamp": 1606985675999,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "s_UpGPt_zi-U",
    "outputId": "dc70ccba-019d-4ed8-d980-6d62a269120c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 4]\n"
     ]
    }
   ],
   "source": [
    "# 讀取內容的方法之一：將型態轉換為串列\n",
    "even_numbers = list(filter(lambda x: x%2==0, numbers))\n",
    "print(even_numbers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oM3qryUSy-9H"
   },
   "source": [
    "### `zip()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "聚合所有疊代物件，將每個疊代物件中的第 `i` 個物件集合為 Tuple（元祖、數組）物件。\n",
    "\n",
    "* [zip() - Python Documentation](https://docs.python.org/3/library/functions.html#zip)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 815,
     "status": "ok",
     "timestamp": 1606985723120,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "DfNGqccsz5Nf",
    "outputId": "44a53880-7b3b-4b29-dfde-032160ba7c87"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('one', 'two', 'three')\n",
      "<class 'tuple'>\n",
      "(1, 2, 3)\n",
      "<class 'tuple'>\n"
     ]
    }
   ],
   "source": [
    "t1 = ('one', 'two', 'three')\n",
    "print(t1)\n",
    "print(type(t1))\n",
    "t2 = (1, 2, 3)\n",
    "print(t2)\n",
    "print(type(t2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 830,
     "status": "ok",
     "timestamp": 1606985755255,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "xbaiL3nS0J8e",
    "outputId": "08667ee7-7597-4e60-f58b-89bba7ce0da6"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<zip at 0x110303288>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 直接套用會回傳 zip 物件\n",
    "zip(t1, t2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 717,
     "status": "ok",
     "timestamp": 1606985761119,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "RasvXoH-0DZp",
    "outputId": "eede5f81-629c-4630-fcb5-5da728211f08"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('one', 1), ('two', 2), ('three', 3)]\n"
     ]
    }
   ],
   "source": [
    "# 讀取內容的方法之一：將型態轉換為串列\n",
    "zipped = list(zip(t1, t2))\n",
    "print(zipped)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 578,
     "status": "ok",
     "timestamp": 1606985779896,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "8CI8F-Vk0MYc",
    "outputId": "273a8d83-be10-4ac8-df58-9efe38c644c2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'one': 1, 'two': 2, 'three': 3}\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "# 延伸應用方法：將多個 Tuples 轉換為字典物件\n",
    "zipped_dict = dict(zipped)\n",
    "print(zipped_dict)\n",
    "print(type(zipped_dict))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FrJR6hv5zA1e"
   },
   "source": [
    "### `reduce()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "將疊代物件中的物件由左而右、兩兩代入函式中。\n",
    "\n",
    "References:\n",
    "\n",
    "* [reduce() - Python Documentation](https://docs.python.org/3/library/functions.html#reduce)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "id": "ScVbqRub01p8"
   },
   "outputs": [],
   "source": [
    "from functools import reduce"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1047,
     "status": "ok",
     "timestamp": 1606986240035,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "xfDC9Jtm0hpV",
    "outputId": "398304c4-2d88-4e43-ebb7-e12c2661a718"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "numbers = list(range(1, 6))\n",
    "print(numbers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1344,
     "status": "ok",
     "timestamp": 1606986240556,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "0I2pS-h61IyJ",
    "outputId": "be23ba72-c0ae-4360-cdc5-63028f3fe9c4"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "15"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "reduce(lambda x, y: x+y, numbers)  # 與 (((1+2)+3)+4)+5 等價"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1215,
     "status": "ok",
     "timestamp": 1606986240562,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "4Zdb3ypv0nat",
    "outputId": "f5cf127f-5227-44b5-cf44-3bbb65db34b0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15\n"
     ]
    }
   ],
   "source": [
    "suqared_sum = reduce(lambda x, y: x+y, numbers)\n",
    "print(suqared_sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3LXFgmMtuLjB"
   },
   "source": [
    "### `print()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "77z-exEkaPD3"
   },
   "source": [
    "`print()` 函式可以搭配一些格式化的手法，更容易湊出需要的字串內容。\n",
    "\n",
    "References:\n",
    "\n",
    "* [printf-style string formatting - Python Documentation](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
    "* [Built-in functions print() - Python Documentation](https://docs.python.org/3/library/functions.html#print)\n",
    "* [str.format()](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
    "* [Format string syntax](https://docs.python.org/3/library/string.html#format-string-syntax)\n",
    "* [Fancier output formatting](https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting)\n",
    "* [PEP 498 -- Literal String Interpolation](https://www.python.org/dev/peps/pep-0498/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Ljn1W3l2dmzN"
   },
   "source": [
    "#### printf-style formatting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "C 語言的寫法。\n",
    "\n",
    "> 備註：個人是不推薦啦。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 2733,
     "status": "ok",
     "timestamp": 1607080439763,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "7WaXNZB6aOFz",
    "outputId": "56df0d6f-23e0-4484-a8a7-398bab8e7f3f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vivi\n"
     ]
    }
   ],
   "source": [
    "myname = 'Vivi'\n",
    "print(myname)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1017,
     "status": "ok",
     "timestamp": 1607080780612,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "4qiCnF-FcWg2",
    "outputId": "cde6d4d5-b0c1-4822-8fbd-5b3e8bcc1ddc"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello Vivi!\n",
      "Hello Vivi!\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello %s!\" % myname)\n",
    "print(\"Hello %(name)s!\" % {'name': myname})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RtX38ahrdtcY"
   },
   "source": [
    "#### Format string syntax"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "搭背字串的 `.format()` 方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "id": "hnMcJcXjeUjm"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vivi\n"
     ]
    }
   ],
   "source": [
    "myname = 'Vivi'\n",
    "print(myname)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 967,
     "status": "ok",
     "timestamp": 1607080771607,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "3qEskychedF6",
    "outputId": "d91a7346-84d8-4f6b-937d-13aff449626e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello Vivi!\n",
      "Hello Vivi!\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello {}!\".format(myname))\n",
    "print(\"Hello {name}!\".format(name=myname))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5vFrg8TDfCAp"
   },
   "source": [
    "#### Fancier output formatting (f-string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[PEP 498](https://www.python.org/dev/peps/pep-0498/) 文件中的標蹹大至上是描述為「字串內插法」。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1089,
     "status": "ok",
     "timestamp": 1607080990323,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "MWwgMfHAfa_5",
    "outputId": "3eb41bfb-3f7f-4190-9bde-d9d2111c96af"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vivi\n"
     ]
    }
   ],
   "source": [
    "myname = 'Vivi'\n",
    "print(myname)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1072,
     "status": "ok",
     "timestamp": 1607081176273,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "bBPVOvzmfdNt",
    "outputId": "1f0c30ea-79da-40cc-86fd-ce33803be1a4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello Vivi!\n"
     ]
    }
   ],
   "source": [
    "print(f\"Hello {myname}!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1125,
     "status": "ok",
     "timestamp": 1607081136043,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "v2-OXsf5f8CF",
    "outputId": "b7879f75-f776-4487-fb0c-f18f421ce6be"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2\n"
     ]
    }
   ],
   "source": [
    "x, y = 1, 2\n",
    "print(x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 625,
     "status": "ok",
     "timestamp": 1607081167644,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "7nvBbun3gBX5",
    "outputId": "c68af9fa-14c7-4a0c-e651-1104262d7289"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x + y = 3\n"
     ]
    }
   ],
   "source": [
    "print(f\"x + y = {x+y}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Si_vmND6uXIw"
   },
   "source": [
    "### `isinstance()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "回傳物件是否屬於某個物件型態。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 941,
     "status": "ok",
     "timestamp": 1607081340466,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "nh10LyXJgtEB",
    "outputId": "bc531a08-4841-439c-f267-e1a279a9cb1c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello world!\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s = \"Hello world!\"\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 731,
     "status": "ok",
     "timestamp": 1607081378241,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "K-I7uXjEgytT",
    "outputId": "9385a538-1960-455b-b3df-97cc5597ab03"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(isinstance(s, str))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xLxww2c1ujMw"
   },
   "source": [
    "### `del()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "先記得功能是刪除物件就好～"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 669,
     "status": "ok",
     "timestamp": 1607081462687,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "pFRFTB9VhFd2",
    "outputId": "3a42d6d4-a37a-4fc7-f9e4-722132eb6059"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "x = 10\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "id": "v6gdv3xqhHYi"
   },
   "outputs": [],
   "source": [
    "del(x)\n",
    "# print(x)  # NameError: name 'x' is not defined"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qPbu-qdWuauN"
   },
   "source": [
    "### `id()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "回傳物件的記憶體位址。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1295,
     "status": "ok",
     "timestamp": 1607081796023,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "PhSn0kWUg-WK",
    "outputId": "f5034b8a-1376-4fee-d3d9-c733fd1cf841"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4531635072\n"
     ]
    }
   ],
   "source": [
    "x = 10\n",
    "print(id(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1020,
     "status": "ok",
     "timestamp": 1607081796024,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "oym5aI2ohU67",
    "outputId": "25b08294-d778-4898-d465-50eea53840c3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4531635392\n"
     ]
    }
   ],
   "source": [
    "# 當不可變型態物件被指定新的值時，其記憶體參照的位址也不一樣了\n",
    "x = 20\n",
    "print(id(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1072,
     "status": "ok",
     "timestamp": 1607081835451,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "loJbhQ6SiF67",
    "outputId": "473ff450-265e-44c9-d097-41bcf0dd8312"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4565799816\n",
      "4565799816\n"
     ]
    }
   ],
   "source": [
    "# 可變型態物件如果沒有調用 .copy() 方法來複製，將會指向同樣的記憶體位置\n",
    "l1 = [1, 2, 3]\n",
    "print(id(l1))\n",
    "l2 = l1\n",
    "print(id(l2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dr2xQU-cuGXR"
   },
   "source": [
    "## Errors and Exceptions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "運作方式如下：\n",
    "\n",
    "1. 執行關鍵字 `try` 與 `except` 之間的內容\n",
    "2. 如果沒有發生例外，則順利將內容執行完畢\n",
    "3. 如果發生錯誤，則比對各個關鍵字 `except` 之後的例外，若符合則執行該區塊的內容\n",
    "4. 無論是否發生例外，皆執行關鍵字 `finally` 區塊內的內容\n",
    "\n",
    "References:\n",
    "\n",
    "* [Errors and Exceptions](https://docs.python.org/3/tutorial/errors.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 5122,
     "status": "ok",
     "timestamp": 1606985026182,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "5q8HqkL8uv2M",
    "outputId": "43ea5a12-71ba-4a37-f896-e9891f525598"
   },
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Please enter a number:  ???\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error occurs! invalid literal for int() with base 10: '???'\n",
      "The whole process is end.\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Please enter a number:  10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The number you input was: 10\n",
      "The whole process is end.\n"
     ]
    }
   ],
   "source": [
    "x = None\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter a number: \"))\n",
    "        print(\"The number you input was:\", x)\n",
    "        break\n",
    "    except Exception as e:  # 捕捉所有例外\n",
    "        print(\"Error occurs!\", e)\n",
    "    finally:\n",
    "        print(\"The whole process is end.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 8094,
     "status": "ok",
     "timestamp": 1606985034921,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "t0R0CrqwwgH8",
    "outputId": "cc0dbb75-1c4a-43eb-9804-838960c11579"
   },
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Please enter a number:  ??????\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Oops!  That was no valid number.  Try again...\n",
      "Error details: invalid literal for int() with base 10: '??????'\n",
      "The whole process is end.\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Please enter a number:  10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The number you input was: 10\n",
      "The whole process is end.\n"
     ]
    }
   ],
   "source": [
    "x = None\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter a number: \"))\n",
    "        print(\"The number you input was:\", x)\n",
    "        break\n",
    "    except ValueError as ve:  # 捕捉 ValueError 例外\n",
    "        print(\"Oops!  That was no valid number.  Try again...\")\n",
    "        print(\"Error details:\", ve)\n",
    "    except Exception as e:  # 捕捉所有其他例外\n",
    "        print(\"Unknown error occurs:\", e)\n",
    "    finally:\n",
    "        print(\"The whole process is end.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_AvizkRajNCZ"
   },
   "source": [
    "## List comprehensions & Dict comprehensions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dKRq9vuc0fXG"
   },
   "source": [
    "另一種為疊代物件中的所有物件套用 `map()` 或 `filter()` 函式，並將所有集合集中在串列 / 字典中的寫法。\n",
    "\n",
    "References:\n",
    "\n",
    "* [PEP 202 -- List Comprehensions](https://www.python.org/dev/peps/pep-0202/)\n",
    "* [PEP 274 -- Dict Comprehensions](https://www.python.org/dev/peps/pep-0274/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1685,
     "status": "ok",
     "timestamp": 1607082048662,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "Zrz1guCcjPay",
    "outputId": "a978ee3a-1cf8-4c2a-95d9-4372689f9bde"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n"
     ]
    }
   ],
   "source": [
    "# 計算疊代物件的平方值\n",
    "l = []\n",
    "\n",
    "for x in range(1, 11):\n",
    "    l.append(x**2)\n",
    "\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1304,
     "status": "ok",
     "timestamp": 1607082102349,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "jfe_1Pc7jfUN",
    "outputId": "d4dee982-7126-4aba-8345-35ca8ff0eeb4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n"
     ]
    }
   ],
   "source": [
    "# 用 map() 函式改寫\n",
    "l = list(map(lambda x: x**2, range(1, 11)))\n",
    "\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 798,
     "status": "ok",
     "timestamp": 1607082124470,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "LPGPFro5joGB",
    "outputId": "53f085ff-ad17-4e97-b9c2-a2be381723a1"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n"
     ]
    }
   ],
   "source": [
    "# 最後用 List comprehension 舉例\n",
    "l = [x**2 for x in range(1, 11)]\n",
    "\n",
    "print(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 4, 6, 8, 10]\n"
     ]
    }
   ],
   "source": [
    "# 另一個例子：用 List comprehension 過濾出 2 的倍數\n",
    "print([x for x in range(1, 11) if x%2==0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tU2gVl-45ps7"
   },
   "source": [
    "## Generators"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pNFf-yId5_HT"
   },
   "source": [
    "生成器中的物件，只在調用 `next()` 函式時產生，節省記憶體空間。\n",
    "\n",
    "References:\n",
    "\n",
    "* [Generators - Python Documentation](https://docs.python.org/3/tutorial/classes.html#generators)\n",
    "* [sys.getsizeof() - Python Documentation](https://docs.python.org/3/library/sys.html?highlight=getsizeof#sys.getsizeof)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "id": "4khM00oW425z"
   },
   "outputs": [],
   "source": [
    "# 範例：製作費氏數列串列\n",
    "l = []\n",
    "\n",
    "def fibs_list(n):\n",
    "    a, b = 0, 1\n",
    "    for _ in range(n):\n",
    "        a, b = b, a + b\n",
    "        l.append(a)\n",
    "    return l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 1, 2, 3, 5]\n"
     ]
    }
   ],
   "source": [
    "print(fibs_list(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 製作生成器的思路：先試著將多個物件 print 出來\n",
    "def fibs_print(n):\n",
    "    a, b = 0, 1\n",
    "    for _ in range(n):\n",
    "        a, b = b, a + b\n",
    "        print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "fibs_print(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 接著，只要把 print() 函式改成 yield 就可以了！\n",
    "def fibs_generator(n):\n",
    "    a, b = 0, 1\n",
    "    for _ in range(n):\n",
    "        a, b = b, a + b\n",
    "        yield a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 1, 2, 3, 5]"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 調用生成器內容的方法之一：轉換型態為串列\n",
    "list(fibs_generator(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 或是調用 next()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "f_5 = fibs_generator(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "print(next(f_5))\n",
    "print(next(f_5))\n",
    "print(next(f_5))\n",
    "print(next(f_5))\n",
    "print(next(f_5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "# 也可以搭配 For loop 調用內容\n",
    "for f in fibs_generator(5):\n",
    "    print(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 1010,
     "status": "ok",
     "timestamp": 1607310039322,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "MYc1lDFN5B_K",
    "outputId": "26bf0299-8091-43a9-ccda-ec8aa3bc6176"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The list contains first 100 Fibonacci numbers consumes 912 bytes\n",
      "The list contains first 1000 Fibonacci numbers consumes 9024 bytes\n"
     ]
    }
   ],
   "source": [
    "# 測試將費氏數列以串列形式生成，將消耗多少記憶體\n",
    "import sys\n",
    "\n",
    "print(\"The list contains first 100 Fibonacci numbers consumes\",sys.getsizeof(fibs_list(100)), \"bytes\")\n",
    "print(\"The list contains first 1000 Fibonacci numbers consumes\",sys.getsizeof(fibs_list(1000)), \"bytes\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 934,
     "status": "ok",
     "timestamp": 1607310076887,
     "user": {
      "displayName": "黃種平",
      "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjCoYcYDAMAK-J-MvClxwWJY0fvKYsny6BL962ZNA=s64",
      "userId": "12486487678081777487"
     },
     "user_tz": -480
    },
    "id": "UX23_Uck4gtC",
    "outputId": "0e3ed38f-5b5f-42a1-fea7-b01493415169"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The generator contains first 100 Fibonacci numbers consumes 88 bytes\n",
      "The generator contains first 1000 Fibonacci numbers consumes 88 bytes\n"
     ]
    }
   ],
   "source": [
    "# 再測試將費氏數列以生成器形式生成，將消耗多少記憶體\n",
    "print(\"The generator contains first 100 Fibonacci numbers consumes\", sys.getsizeof(fibs_generator(100)), \"bytes\")\n",
    "print(\"The generator contains first 1000 Fibonacci numbers consumes\", sys.getsizeof(fibs_generator(1000)), \"bytes\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "authorship_tag": "ABX9TyNJ5MeqIxCDKnV3nrVP66KP",
   "collapsed_sections": [],
   "name": "Python Basics - Chapter 8 - Miscellaneous.ipynb",
   "provenance": [],
   "toc_visible": true
  },
  "jupytext": {
   "formats": "ipynb,py:light"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
